package com.sdx.controller;

import com.ibeetl.admin.core.file.FileService;
import com.ibeetl.admin.core.util.UUIDUtil;
import com.ibeetl.admin.core.web.JsonResult;
import org.apache.commons.lang3.StringUtils;
import org.beetl.ext.fn.Json;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;

/**
 * @ClassName FileMgrController
 * @Description: 文件上传
 * @author: tanbaocai
 * @date: 2018/10/30 11:07
 */
@RequestMapping("/filemgr")
@Controller
public class FileMgrController {
	private static final Logger log = LoggerFactory.getLogger(FileMgrController.class);

	@Resource
	private FileService fileService;

	/**
	 * 文件上传
	 * @param subPath 文件存放路径，相对路径
	 * @param fileName 文件名，可不传，不传则自动生成文件名
	 * @param uploadFile
	 * @return
	 */
	@PostMapping("/upload.json")
	@ResponseBody
	public JsonResult<String> upload(String subPath,String fileName,MultipartFile uploadFile) {
		JsonResult<String> jsonResult = JsonResult.success();

		String root = fileService.getRoot();
		if (!subPath.endsWith("/")) {
			subPath = subPath+"/";
		}
		String dir = root+subPath;
		File dirFile = new File(dir);
		if(!dirFile.exists()) {
			dirFile.mkdirs();
		}
		if (StringUtils.isEmpty(fileName)) {
			String originalFile = uploadFile.getOriginalFilename();
			int dotIdex = originalFile.lastIndexOf(".");
			String postfix = originalFile.substring(dotIdex);
			fileName = UUIDUtil.uuid() + postfix;
		}
		File target = new File(dirFile,fileName);
		try {
			uploadFile.transferTo(target);
		} catch (IOException e) {
			log.error("uploadfile",e);
			jsonResult = JsonResult.failMessage("上传文件失败，"+e.getMessage());
		}
		fileName = subPath+fileName;
		jsonResult.setData(fileName);
		return jsonResult;
	}

	/**
	 * 删除文件
	 * @param filePath
	 * @return
	 */
	@PostMapping("/delete.json")
	@ResponseBody
	public JsonResult delete(String filePath) {
		JsonResult result = JsonResult.success();
		String root = fileService.getRoot();
		filePath = root+filePath;
		File file = new File(filePath);
		file.delete();
		return result;
	}

	/**
	 * 删除文件
	 * @param coverFile
	 * @return
	 */
	@PostMapping("/upload")
	@ResponseBody
	public String upload(MultipartFile coverFile) {
		
		return "";
	}
}
